package ldh.common.testui.model;

import com.google.gson.reflect.TypeToken;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import ldh.common.json.JsonViewFactory;
import ldh.common.testui.constant.ParamType;
import ldh.common.testui.util.DateUtil;
import lombok.Data;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by ldh123 on 2017/6/8.
 */
@Data
public class TestHttpParam {

    private Integer id;
    private Integer testHttpId;
    private String name;
    private String content;
    private ParamType paramType;
    private BooleanProperty enable = new SimpleBooleanProperty(true);

    public TestHttpParam() {
        enable.addListener((b, o, n)->{
            System.out.println("change!!!!!!:" +n);
        });
    }

    public List<TestCookie> toTestCookies() {
        if (paramType != ParamType.Cookie) {
            throw new RuntimeException("不是cookie");
        }
        return JsonViewFactory.create().fromJson(content, new TypeToken<List<TestCookie>>(){}.getType());
    }

    public List<Cookie> toCookies() {
        List<TestCookie> testCookies = toTestCookies();
        List<Cookie> cookies = new ArrayList();
        testCookies.forEach(testCookie -> {
            BasicClientCookie cookie = new BasicClientCookie(testCookie.getName(), testCookie.getValue());
            cookie.setDomain(testCookie.getDomain());
            cookie.setPath(testCookie.getPath());
            cookie.setSecure(testCookie.isSecure());
            Date date = DateUtil.parse(testCookie.getExpires(), "yyyy-MM-dd HH:mm:ss");
            cookie.setExpiryDate(date);
            cookies.add(cookie);
        });
        return cookies;
    }

    public BooleanProperty enableProperty() {
        if (enable == null) {
            enable = new SimpleBooleanProperty(true);
        }
        return enable;
    }

    public void setEnable(boolean isEnable) {
        enableProperty().set(isEnable);
    }

    public boolean getEnable() {
        return enableProperty().get();
    }
}
